package com.woniuxy.rabbitmq.baseapi.mq10dlx;

/**
 * description: Consumer <br>
 * date: 2022/1/10 5:51 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 生产者发送消息
 */
public class ConsumerTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接工厂：配置连接参数，创建连接对象
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.13.33");
        //设置虚拟主机：类似于mysql数据库服务器中的一个具体数据库，默认的就是/
        connectionFactory.setVirtualHost("/");
        //消息通信端口
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //连接对象
        Connection connection = connectionFactory.newConnection();
        //连接信道
        Channel channel = connection.createChannel();
        //定义交换机
        //string exchange 交换机名字
        //BuiltinExchangeType type 交换机的类型
        //一组正常接收消息的交换机和队列，配置了队列和死信相关的属性
        channel.exchangeDeclare("exchangedlxtest", BuiltinExchangeType.TOPIC);
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "exchangedlx");
        arguments.put("x-dead-letter-routing-key", "dlx");
        channel.queueDeclare("queuedlxest", true, false, false, arguments);
        channel.queueBind("queuedlxest", "exchangedlxtest", "#.dlxtest.#");

        //定义死信交换机和死信路由
        channel.exchangeDeclare("exchangedlx", BuiltinExchangeType.TOPIC);
        //死信队列
        channel.queueDeclare("queuedlx", true, false, false, null);
        channel.queueBind("queuedlx", "exchangedlx", "#.dlx.#");
        //限流:指定每次从队列中取多少个消息消费
//        channel.basicQos(1);
//        //手动确认
//        channel.basicConsume("queuetest", false,
//                new DefaultConsumer(channel) {
//                    //String consumerTag, 消费者标记，系统会自动分配
//                    //Envelope envelope, 信封，封装和当前消息相关的信息，后面的手动确认要使用
//                    // AMQP.BasicProperties properties, 发送消息时指定的附加属性
//                    // byte[] body：消息体
//                    @SneakyThrows
//                    @Override
//                    public void handleDelivery(String consumerTag, Envelope envelope,
//                                               AMQP.BasicProperties properties, byte[] body)
//                            throws IOException {
//                        System.out.println("处理邮件消息:" + new String(body));
//                        channel.basicAck(envelope.getDeliveryTag(), false);
//                        System.out.println("-----------------------------");
//
//                    }
//                });
        //消费者启动后一直监听队列，处理消息，一般不关闭
    }
}
